package com.study.multithreading;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 创建人： HBZ，时间： 2017/5/22 11:00.
 * 说明：ArrayList线程不安全，经过Collections.synchronizedList(new ArrayList<>())转换后变成线程安全，
 * 类似Collections.synchronizedMap(new HashMap<>())也是线程安全的
 */
public class ArrayListTest {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            List<Object> list = Collections.synchronizedList(new ArrayList<>());
            Thread a = new Thread(new AddThread1(list, "a"));
            Thread b = new Thread(new AddThread1(list, "b"));
            Thread c = new Thread(new AddThread1(list, "c"));
            Thread d = new Thread(new AddThread1(list, "d"));
            Thread e = new Thread(new AddThread1(list, "e"));
            Thread f = new Thread(new AddThread1(list, "f"));
//            a.start();
//            b.start();
//            c.start();
//            d.start();
//            e.start();
//            f.start();
//            a.join();
//            b.join();
//            c.join();
//            d.join();
//            e.join();
//            f.join();
            System.out.println(list.size() + "---" + list);
        }
    /*    for (int i = 0; i < 1000; i++) {
            List<String> list = new ArrayList<String>();
            Thread a = new Thread(new AddThread2(list, "a"));
            Thread b = new Thread(new AddThread2(list, "b"));
            Thread c = new Thread(new AddThread2(list, "c"));
            Thread d = new Thread(new AddThread2(list, "d"));
            Thread e = new Thread(new AddThread2(list, "e"));
            Thread f = new Thread(new AddThread2(list, "f"));
            a.start();
            b.start();
            c.start();
            d.start();
            e.start();
            f.start();
            a.join();
            b.join();
            c.join();
            d.join();
            e.join();
            f.join();
            System.out.println(list + "---" + list.size());
        }*/

    }

    static class AddThread1 implements Runnable {
        List<Object> list;
        String string;

        public AddThread1(List<Object> list, String string) {
            this.list = list;
            this.string = string;
        }

        public void run() {
            list.add(string);
        }
    }

    static class AddThread2 implements Runnable {
        List<String> list;
        String string;

        public AddThread2(List<String> list, String string) {
            this.list = list;
            this.string = string;
        }

        public void run() {
            list.add(string);
        }
    }
}
